package sound;

import java.io.BufferedInputStream;
import java.io.InputStream;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;

/**
* @file Machine.java
*
* @brief Diese Datei enthält die Machine-Klasse.
*
* @author Alrik Künne
*
* @date 01.06.2012 - erste Version
* @date 19.06.2012 - einige Veränderungen, Multi-Threading
**/

/** 
* @class  Machine
* 
* @brief die Soundmaschine, die Sounds in einem eigenen Thread spielt
* 
* Package: Sound
*/ 
public class Machine {

	/** 
	* @brief Spielt den Sound von einem File/URL
	*/ 
	public static synchronized void playSound(final String url) {
	    new Thread(new Runnable() { // the wrapper thread is unnecessary, unless it blocks on the Clip finishing, see comments
	      public void run() {
	        try {
	          
	          InputStream audioSrc = getClass().getResourceAsStream(url);
	          InputStream bufferedIn = new BufferedInputStream(audioSrc);
	          AudioInputStream inputStream = AudioSystem.getAudioInputStream(bufferedIn);
	          
	          //AudioInputStream inputStream = AudioSystem.getAudioInputStream(Machine.class.getResourceAsStream(url));
	          
	          AudioFormat format = inputStream.getFormat();
	          DataLine.Info info = new DataLine.Info(Clip.class, format);
	          Clip clip = (Clip)AudioSystem.getLine(info);
	          // }
	          //Clip clip = AudioSystem.getClip();
	          
	          
	          clip.open(inputStream);
	          clip.start(); 
	        } catch (Exception e) {
	          System.err.println(e.getMessage());
	        }
	      }
	    }).start();
	  }
}